package thread_pool;

import org.junit.Test;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @describe: 类描述信息
 * @author: morningcat.zhang
 * @date: 2019/4/18 1:02 PM
 */
public class ExecutorTest {

    @Test
    public void test1() throws IOException {
        ArrayBlockingQueue workQueue = new ArrayBlockingQueue(20);
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(5, 20, 1, TimeUnit.SECONDS, workQueue, new TestThreadFactory(), new TestRejectedExecutionHandler());
        for (int i = 0; i < 50; i++) {
            executorService.execute(() -> {
                System.out.println(Thread.currentThread().getName() + " ---> 添加任务");
                try {
                    Thread.sleep(new Random().nextInt(5000));
                    //Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });

            System.out.println(Thread.currentThread().getName() + "------ " + i + " ---> ");
        }

        new Thread(() -> {
            // executorService.getActiveCount() > 0
            while (true) {
                System.out.println(Thread.currentThread().getName() + " ------> " + executorService.getPoolSize() + " ---> " + executorService.getActiveCount());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "【监控线程】").start();

        System.in.read();

    }

    @Test
    public void test2() {
        ArrayBlockingQueue workQueue = new ArrayBlockingQueue(20);
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(5, 20, 1, TimeUnit.SECONDS, workQueue, new TestThreadFactory(), new TestRejectedExecutionHandler());
        System.out.println(Thread.currentThread().getName() + " ------> " + executorService.getPoolSize() + " ---> " + executorService.getActiveCount());
        executorService.getCorePoolSize();
    }

    @Test
    public void test3() {

    }
}
